package cn.pconline.autoclub.service.bbssync;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserLimit;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.UserLimitService;
import cn.pconline.autoclub.util.dyna.TopicDyna;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 论坛发贴同步到车友会
 * @author zhouruxuan
 * @date 2014年12月3日 上午10:55:40
 * {"agent":0,"authorId":72402,"containImage":true,"createAt":1418381225612,"createIp":"192.168.32.66","forumId":19017,"forumName":"风花雪月","forumUrl":"","image1":"","images":[{"height":933,"seq":1,"url":"","width":700}],"key":"autobbs.topic.create5805763","lastPostAt":1418381225612,"photoCount":1,"pick":0,"postMessage":"","recommend":0,"routeKey":"autobbs.topic.create","tid":5805763,"title":"1212","topicAuthorId":72402,"topicAuthorName":"wbxuan","topicAuthorUrl":"","topicCreateAt":1418381225612,"topicId":5805763,"topicReplyCount":0,"topicUrl":"","type":""}
 */
public class SyncCreateTopicService extends BbsSyncPetrolService {
	@Autowired
	private DynaService dynaService;
	
	@Autowired
	private PetrolService petrolService;
	
	@Autowired
    private UserLimitService limitService;
	
	//发帖子时，不同的发帖入口，有独立的Agent
	private final static int agent_0 = 0;//来自太平洋汽车网PC客户端
	private final static int agent_1 = 1;//来自太平洋汽车网iPhone客户端
	private final static int agent_2 = 2;//来自太平洋汽车网Android客户端
	private final static int agent_3 = 3;//来自太平洋汽车网全新论坛iPhone客户端
	private final static int agent_4 = 4;//来自太平洋汽车网全新论坛Android客户端
	private final static int agent_5 = 5;//太平洋汽车网触屏版网友
	private final static int agent_6 = 6;//来自中国车友会iPhone客户端
	private final static int agent_7 = 7;//来自中国车友会Android客户端
	
	@Override
    protected int addPetroltoMember(ClubMember clubMember, JSONObject msg) {
	    ClubIntegral topicPetrol = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC); // 油值表
	    int addTotal = topicPetrol.getPetrol();
	    String reason = topicPetrol.getName() + "(topic-" + getTopicId(msg) + ")";
	    petrolService.addOnlyPersonWithinLimit(clubMember, topicPetrol.getIntegralId(), topicPetrol.getPetrol(), reason, true);
	    //新发的帖子不能立即是精华或者推荐
        return addTotal;
    }

    private long getTopicId(JSONObject msg) {
        return msg.getLongValue("topicId");
    }

    @Override
    protected int addPetroltoClub(Club club, JSONObject msg) {
        long userId = getUserId(msg);
        ClubMember clubMember = null;
        if(userId > 0) {
            clubMember = memberService.findClubMemberByUserId(userId);
            if(clubMember != null) {
                UserLimit userLimit = limitService.getMemberLimit(clubMember.getId());
                if (userLimit == null || userLimit.getPetrol() < UserLimit.DAILY_PERSON_LIMIT) { // 未满限制
                    ClubIntegral topicPetrol = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC); // 油值表
                    String reason = topicPetrol.getName() + "(topic-" + getTopicId(msg) + ")";
                    petrolService.addToClubWithinLimit(club.getClubId(), topicPetrol.getIntegralId(), topicPetrol.getPetrol(), reason, true);
                    return topicPetrol.getPetrol();
                } else {
                    log.info("user reach the limit[{}]petrol, no longer add petrol to club!", UserLimit.DAILY_PERSON_LIMIT);
                }
            }
        }
        return 0;
    }
    
    @Override
    protected long getUserId(JSONObject msg) {
        return msg.getLongValue("topicAuthorId");
    }
	
	@Override
	public void process(JSONObject msg, ClubMember clubMember) {
		//验证用户
	    long userId = getUserId(msg);
        if (userId <= 0L) {
            log.info("not userId-{}", userId);
            return;
        }

        //判断用户是否登录
        User user = userService.authUser(userId);
        if (user == null || user.getUid() == 0L) {
            log.info("not found user-{}", userId);
            return;
        }
        long clubId = 0;
        if(clubMember != null) {
            clubId = clubMember.getClubId();
        }
        TopicDyna topicDyna = this.parseActionLog2DynaInfo(msg, clubId);
        //创建帖子油值
        int petrol = this.calculateDynaPetrol(topicDyna);
        //创建帖子
      //设置topic对象
        topicDyna.setPetrol(petrol);
        List<DynaImage> dynaImages = this.parseActionLog2DynaImages(msg, userId);
        dynaService.createTopicDyna(topicDyna, dynaImages);
	}
	
	/**
	 * @param json转topic,只有创建帖子的时候有效
	 * @param clubId
	 * @return
	 */
    private TopicDyna parseActionLog2DynaInfo(JSONObject msg, long clubId) {
        TopicDyna topicDyna = new TopicDyna();
        topicDyna.setTopicId(getTopicId(msg));
        topicDyna.setClubId(clubId);
        topicDyna.setForumId(msg.getLongValue("forumId"));
        topicDyna.setUserId(msg.getLongValue("topicAuthorId"));
        topicDyna.setForumName(StringUtils.defaultString(msg.getString("forumName")));
        topicDyna.setLastPostAt(new Date(msg.getLongValue("lastPostAt")));
        topicDyna.setCreateDate(new Date(msg.getLongValue("topicCreateAt")));
        topicDyna.setLastPostBy(msg.getLongValue("topicAuthorId"));
        topicDyna.setLastPostName((msg.getString("topicAuthorName")));
        topicDyna.setMessage(StringUtils.defaultString(msg.getString("postMessage")));
        topicDyna.setTopicTitle(StringUtils.defaultString(msg.getString("title")));
        topicDyna.setPick(msg.getIntValue("pick") != DynaInfo.PICK_NO ? 
                DynaInfo.PICK_YES : DynaInfo.PICK_NO);
        topicDyna.setRecommend(msg.getIntValue("recommend") != DynaInfo.RECOMMEND_NO ? 
                DynaInfo.RECOMMEND_YES: DynaInfo.RECOMMEND_NO);
        topicDyna.setPostCount(msg.getIntValue("topicReplyCount"));
        topicDyna.setCreateName(msg.getString("topicAuthorName"));//论坛传的是nickname
        topicDyna.setType(msg.getString("type"));//帖子类型，question为提问帖标记
        int agent =msg.getIntValue("agent");
        if(agent ==  agent_6 || agent == agent_7) {//从车友会APP发的帖子
        	topicDyna.setAppTitle(StringUtils.defaultString(msg.getString("appTitle")));
        } else {//从非车友会APP发的帖子
        	topicDyna.setAppTitle(StringUtils.defaultString(msg.getString("title")));
        }
        return topicDyna;
    }
    
    /**
     * 计算创建帖子油值
     * @param topicDyna
     * @param typeId
     * @return
     */
    public int calculateDynaPetrol(TopicDyna topicDyna) {
        long clubId = topicDyna.getClubId();
        if(clubId == 0) {
            return 0;
        }
        Club club = clubService.getClub(clubId);
        if(club == null || club.getStatus() != Club.STATUS_PASS) {
            return 0;
        }
        ClubIntegral topicPetrol = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC); // 油值表
        int dynaPetrol = topicPetrol.getPetrol();
        return dynaPetrol;
    }
    
    /**
     * 帖子图片列表
     * @param msg
     * @param userId
     * @return
     */
    private List<DynaImage> parseActionLog2DynaImages(JSONObject msg, long userId) {
        JSONArray jsonArray = msg.getJSONArray("images");
        if(jsonArray != null) {
            List<DynaImage> list = new ArrayList<DynaImage>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = JSONObject.parseObject(jsonArray.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(json.getIntValue("seq"));
                dynaImage.setUrl(json.getString("url"));
                dynaImage.setWidth(json.getIntValue("width"));
                dynaImage.setHeight(json.getIntValue("height"));
                if (StringUtils.isBlank(dynaImage.getUrl())) {
                    continue;
                }
                list.add(dynaImage);
            }
            return list;
        }
        return null;
    }
}
